import json.encoder
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

base_dir=os.path.abspath(os.path.dirname(__file__))
app=Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI']=('sqlite:///'+os.path.join(base_dir,'data.sqlite'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
app.config['SQLALCHEMY_COMMIT_TEARDOWN']=True
db=SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    sex=db.Column(db.Integer,nullable=False,default=0)
    age = db.Column(db.Integer, nullable=False, default=0)
    status = db.Column(db.Integer, nullable=False,default=0)
    createdate=db.Column(db.DateTime,nullable=False,server_default=text('CURRENT_TIMESTAMP'))

    def __repr__(self):
        return f"{self.id},{self.username}"

@app.route("/initdb")
def initdb():
    db.drop_all()
    db.create_all()
    return "数据库初始化成功.."

@app.route("/add")
def addData():
    user=User(username="张三",password="123",age=20,status=1)
    #添加单条记录
    db.session.add(user)
    db.session.commit()
    return "单条数据添加成功！"

@app.route("/adds")
def addDatas():
    u1=User(username="李四",password="124",age=19,status=1)
    u2=User(username="王五",password="125",age=18,status=1)
    u3=User(username="赵六",password="126",age=17,status=1)
    u4=User(username="冯七",password="127",age=16,status=1)
    #添加多条记录
    db.session.add_all([u1,u2,u3,u4])
    db.session.commit()
    return "多条数据添加成功！"

@app.route("/getAll")
def getAll():
    users=db.session.query(User).all()
    return str(users)

@app.route("/update")
def update():
    user=User.query.get(1)
    user.username="张三三"
    db.session.commit()
    return "数据修改成功"

@app.route("/del")
def delData():
    user=User.query.filter(User.id==3).first()
    db.session.delete(user)
    db.session.commit()
    return "数据删除成功"





if __name__=="__main__":
    app.run(debug=True)


